﻿using Jinndev.UI;
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;

namespace Jinndev {

    /// <summary>
    /// 万片编辑器
    /// </summary>
    public class TileEditorUI : BaseUIBehaviour, IEscape {

        #region static
        public static readonly string PATH = "Prefab/UI/MapEditor/Tile/TileEditorUI";

        public static TileEditorUI Create() {
            return UIManager.Instance.Add<TileEditorUI>(PATH, UIParam.FullScreen);
        }
        #endregion

        [Header("标题栏")]
        public Text textFile;

        [Header("工具栏")]
        public InputField inputSearch;

        [Header("瓦片")]
        public GridView tileView;
        public GameObject tileItemPrefab;

        [Header("图片")]
        public GridView textureView;
        public GameObject textureItemPrefab;

        private List<TileConfig> tileConfigList = new List<TileConfig>();
        private List<string> textureList = new List<string>();

        private void Awake() {
            tileView.onCreateItem = OnCreateTileItem;
            tileView.onUpdateItem = OnUpdateTileItem;

            textureView.onCreateItem = OnCreateTextureItem;
            textureView.onUpdateItem = OnUpdateTextureItem;

            textFile.text = MapUtil.TileConfigFile;

            EventManager.AutoSet(gameObject, CustomEvent.LocateTexture, OnLocateTexture);
        }

        private void Start() {
            ReloadTextures();

            MapUtil.LoadTileConfig();
            MapUtil.ReloadTileConfigList(tileConfigList, null);
            MapUtil.FixLostTexturePath(tileConfigList, textureList);

            tileView.Reload(tileConfigList.Count);
        }

        private void ReloadTiles() {
            MapUtil.ReloadTileConfigList(tileConfigList, inputSearch.text);
            tileView.Reload(tileConfigList.Count);
        }

        private void ReloadTextures() {
            textureList.Clear();
            string[] files = Directory.GetFiles(Setting.Instance.mapTextureRootDir, "*.png", SearchOption.AllDirectories);
            foreach (string file in files) {
                string name = Path.GetFileNameWithoutExtension(file);
                if (name == "_" || name.StartsWith("毛坯")) {
                    continue;
                }
                string path = file.Substring(Setting.Instance.mapTextureRootDir.Length + 1).Replace("\\", "/");
                textureList.Add(path);
            }
            textureView.Reload(textureList.Count);
        }

        private GameObject OnCreateTileItem() {
            GameObject obj = Instantiate(tileItemPrefab);
            var tileItem = obj.GetComponent<TileItemUI>();
            tileItem.onClickDelete = OnClickDeleteTile;
            return obj;
        }

        private void OnUpdateTileItem(GameObject obj, int index) {
            var tileItem = obj.GetComponent<TileItemUI>();
            tileItem.Refresh(tileConfigList[index]);
        }

        /// <summary> 点击新建瓦片 </summary>
        public void OnClickCreateTile() {
            var config = new TileConfig();
            config.id = MapUtil.NewTileID();
            config.anchor = Float2.half;

            MapUtil.tileConfigs.Add(config.id, config);
            tileConfigList.Add(config);

            tileView.Reload(tileConfigList.Count);
            tileView.scrollRect.verticalNormalizedPosition = 0;
            tileView.scrollRect.DOVerticalNormalizedPos(0, 0.3f);//.SetEase(Ease.OutExpo);
        }

        /// <summary> 点击保存 </summary>
        public void OnClickSave() {
            MapUtil.SaveTileConfig();
        }

        /// <summary> 点击搜索 </summary>
        public void OnClickSearch() {
            ReloadTiles();
        }

        /// <summary> 点击自动生成全部 </summary>
        public void OnClickAutoCreateAll() {
            int count = 0;
            foreach (string texture in textureList) {
                var config = FindConfigByTexture(texture);
                if (config == null) {
                    string name = Path.GetFileNameWithoutExtension(texture);

                    config = new TileConfig();
                    config.id = MapUtil.CheckSameTileId(name);
                    config.anchor = Float2.half;
                    config.lf = texture;

                    MapUtil.tileConfigs.Add(config.id, config);
                    tileConfigList.Add(config);
                    count++;
                }
            }
            if (count > 0) {
                tileView.Reload(tileConfigList.Count);
                NotificationUI.Create($"生成了 {count} 个配置");
            }
            else {
                NotificationUI.Create($"没有需要生成的配置");
            }
        }

        private TileConfig FindConfigByTexture(string texture) {
            foreach (TileConfig config in tileConfigList) {
                if (config.lf == texture || config.rf == texture || config.lb == texture || config.rb == texture) {
                    return config;
                }
            }
            return null;
        }

        /// <summary> 点击清空搜索框 </summary>
        public void OnClickClearSearch() {
            inputSearch.text = string.Empty;
            ReloadTiles();
        }

        /// <summary> 点击删除瓦片 </summary>
        public void OnClickDeleteTile(TileConfig config) {
            tileConfigList.Remove(config);
            MapUtil.tileConfigs.Remove(config.id);
            tileView.Reload(tileConfigList.Count);
        }


        private GameObject OnCreateTextureItem() {
            GameObject obj = Instantiate(textureItemPrefab);
            return obj;
        }

        private void OnUpdateTextureItem(GameObject obj, int index) {
            var textureItem = obj.GetComponent<TextureItemUI>();
            textureItem.Refresh(textureList[index]);
        }

        /// <summary> 定位贴图 </summary>
        private void OnLocateTexture(EventData eventData) {
            string texturePath = eventData.FirstArg as string;
            if (string.IsNullOrEmpty(texturePath)) {
                return;
            }
            // TODO
        }

        public override void Destroy() {
            DialogUI.CreateConfirm("退出", "是否保存修改?", () => {
                // yes
                OnClickSave();
                Destroy(gameObject);
            }, () => {
                // no
                Destroy(gameObject);
            }, () => {
                // close
            });
        }

        public EscapeResult OnEscape() {
            Destroy();
            return EscapeResult.Cancel;
        }

    }

}
